/*!
 * Menu create.
 *
 * Depends:
 *  jquery.ui.widget.js
 */
(function($, undefined) {
	$.widget('ui.aywMenu', {
		options: {
			isQuick: true
		},

		_create: function() {
			var self = this,
				$anchor,
				$menuItems = $(),
				$menuTrigger = $();

			if (this.options.isQuick) {
				$menuItems = self.element.add('li', self.element);
				$menuItems.has('ul').children('a').button({
					icons: {
						primary: '',
						secondary: 'ui-icon-triangle-1-e'
					}
				})
				.filter(':first').find('.ui-button-text')
				.removeClass('ui-button-text')
				.addClass('ui-button-text-qmenu');
				$menuItems.find('a:not(".ui-button")').button();
			} else {
				$menuItems = self.element.find('li');
			}

			$menuItems.mouseleave(function(e) {
				var $this = $(this);
				$('ul', this).fadeOut();
				if ($this.closest('ul').hasClass('menu_root')) {
					$this.children('a:first').css({
						backgroundColor: '',
						color: '#ffffff',
						border: '0'
					});
				}
			});

			$menuItems.children('a').bind('mouseenter.' + self.widgetName, function(event) {
				var menu = $(this).next('ul'),
					posOptions;
				if (menu.is(':visible')) {
					return false;
				}
				if ($(this).parents('ul:first').hasClass('menu_root')) {
					$(this).css({
						backgroundColor: '#ffffff',
						color: '#000000'
						//position:'absolute',
						//zIndex:1
					});
					posOptions = {
						my: 'left top',
						at: 'left bottom',
						//offset: '0 -1',
						of: this
					};
				} else if ($(this).parent().hasClass('qmenu')) {
					posOptions = {
						my: 'left top',
						at: 'left bottom',
						//offset: '0 -1',
						of: this
					};
				} else {
					posOptions = {
						my: 'left top',
						at: 'right top',
						of: this
					};
				}
				menu.menu('deactivate').show().css({
					top: 0,
					left: 0,
					position: 'absolute'
				}).position(posOptions);

				$(document).one('click', function() {
					menu.hide();
				});
				return false;
			})
			.find('.ui-menu-icon-add-tag')
			.hover(function(e) {
				$(this).toggleClass('ui-menu-icon-add-tag-on');
			})
			.click(function(e) {
				var href = $(this).data('href');
				if (href) {
					window.location.href = href;
				}
				return false;
			})
			.end()
			.next()
			.hide()
			.menu({ // @todo Menu have performance issues.
				selected: function(e, ui) {
					var $that = ui.item.find('a:first'),
						href = $that.attr('href'),
						_callbacks = $(ui.item).closest('ul').attr('callbacks');
					if (_callbacks) {
						_json = $.parseJSON(_callbacks);
						if (_json.click) {
							var func = eval(_json.click.callback);
							if ($.isFunction(func))
								if ( _json.click.params) 
									return func.call($that, _json.click.params);
								else 
									return func.call($that);
						}
					}					
					
					$(this).hide();
					href && (window.location = href);
				},
				input: $(this)
			});
		}
	});
})(jQuery);
